package com.tianyu.inspection.controller;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tianyu.inspection.common.Constants;
import com.tianyu.inspection.common.enums.RoState;
import com.tianyu.inspection.common.annotation.Permission;
import com.tianyu.inspection.common.component.AppConstants;
import com.tianyu.inspection.common.component.Validate;
import com.tianyu.inspection.entity.Camera;
import com.tianyu.inspection.entity.User;
import com.tianyu.inspection.entity.model.OperateMo;
import com.tianyu.inspection.entity.model.QueryMo;
import com.tianyu.inspection.entity.vo.Ro;
import com.tianyu.inspection.entity.vo.ServiceRo;
import com.tianyu.inspection.service.api.ICameraService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description 施工单位接口
 * @Date 2021/1/15 - 18:12
 **********************************/

@Slf4j
@RestController
@RequestMapping("/api/2.0/camera")
public class CameraController {

    @Resource
    private ICameraService cameraService;

    @Resource
    private Validate validateModel;

    @Resource
    private ValueOperations<String, Object> valueOperations;

    @Resource
    private AppConstants appConstants;

    @GetMapping(value = "/list")
    @Permission(value = 4, tags = Constants.API_PATROL)
    public Ro<IPage<Camera>> getPageList(HttpServletRequest request, @RequestHeader("u-projectId") Integer projectId,
                                         @RequestHeader("u-uid") Integer userId) {
        QueryMo queryMo = QueryMo.getQueryMo(request);
        Ro<IPage<Camera>> ro = new Ro<>();
        int roleId = (int) request.getAttribute("roleId");
        if (roleId > 1) {
            User loginUser = (User) valueOperations.get(appConstants.redisUserKey + userId);
            if (Objects.nonNull(loginUser)) {
                final String cameraTypeUse = loginUser.getCameraTypeUse();
                try {
                    final Map<String, JSONArray> modelMap = new HashMap<>(1);
                    final JSONArray jsonArray = JSONArray.parseArray(cameraTypeUse);
                    if (Objects.isNull(jsonArray) || jsonArray.size() == 0) {
                        return ro.setResultEnum(RoState.FAIL).setMessage("类型未配置");
                    } else {
                        modelMap.put("camera_type_id", jsonArray);
                    }
                    queryMo.setInMap(modelMap);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
        queryMo.build(Camera.class, projectId);
        return ro.setContent(cameraService.searchListPage(queryMo));
    }

    @GetMapping(value = "/{id}")
    @Permission(value = 4, tags = Constants.API_PATROL)
    public Ro<Camera> getOne(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId) {
        Ro<Camera> ro = new Ro<>();
        if (Objects.isNull(id)) {
            return ro.setResultEnum(RoState.PARAMS_MISS_ERROR);
        }
        QueryMo queryMo = new QueryMo();
        queryMo.put("id", id);
        queryMo.build(Camera.class, projectId);
        Camera camera = cameraService.selectOne(queryMo);
        if (Objects.isNull(camera)) {
            ro.setMessage("未查询到数据");
        } else {
            ro.setContent(camera);
        }
        return ro;
    }

    @PostMapping(value = "/insert")
    @Permission(value = 2, tags = Constants.API_ADMIN)
    public Ro<Camera> insert(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId) {
        Ro<Camera> ro = new Ro<>();
        operateMo.createBuild(Camera.class, projectId);
        if (operateMo.getEntity().size() == 0) {
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        String number = (String) operateMo.getEntity().get("number");
        Integer cameraTypeId = (Integer) operateMo.getEntity().get("cameraTypeId");
        Integer projectId1 = (Integer) operateMo.getEntity().get("projectId");
        Integer pipelineId = (Integer) operateMo.getEntity().get("pipelineId");
        if (Objects.isNull(cameraTypeId)) {
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[cameraTypeId]");
        } else {
            if (validateModel.cameraTypeIdValidate(cameraTypeId)) {
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[cameraTypeId],值不存在");
            }
        }
        if (Objects.isNull(projectId1)) {
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[projectId]");
        } else {
            if (validateModel.projectIdValidate(projectId1)) {
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
            }
        }
        if (Objects.nonNull(number)) {
            final Camera camera = validateModel.cameraNumberValidate(number, projectId1);
            if (Objects.nonNull(camera)) {
                if (camera.getState().equals(0)) {
                    return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[number],值已存在");
                } else {
                    delete(camera.getId(), projectId1);
                }
            }
        }
        if (Objects.nonNull(pipelineId)) {
            if (validateModel.pipelineIdValidate(Integer.parseInt(pipelineId.toString()), Integer.parseInt(projectId1.toString()))) {
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (!cameraService.insert(operateMo)) {
            ro.setResultEnum(RoState.FAIL);
        }
        return ro;
    }

    @PatchMapping(value = "/modify")
    @Permission(value = 2, tags = Constants.API_ADMIN)
    public Ro<Camera> modify(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId) {
        Ro<Camera> ro = new Ro<>();
        final ServiceRo serviceRo = operateMo.updateBuild(Camera.class, projectId);
        if (!serviceRo.getResult()) {
            return ro.setResultEnum(RoState.FAIL).setMessage(serviceRo.getMessage());
        }
        if (operateMo.getEntity().size() == 0) {
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        if (Objects.isNull(operateMo.get("id"))) {
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少[id]字段,请传参后重试");
        }
        Integer id = (Integer) operateMo.get("id");
        String number = (String) operateMo.getEntity().get("number");
        Object cameraTypeId = operateMo.getEntity().get("cameraTypeId");
        Object pipelineId = operateMo.getEntity().get("pipelineId");
        Integer projectId1 = (Integer) operateMo.getEqMap().get("project_id");
        if (Objects.nonNull(cameraTypeId)) {
            if (validateModel.cameraTypeIdValidate(Integer.parseInt(cameraTypeId.toString()))) {
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[cameraTypeId],值不存在");
            }
        }
        if (Objects.nonNull(number)) {
            final Camera camera = validateModel.cameraNumberValidate(number, projectId1);
            if (Objects.nonNull(camera) && (!camera.getId().equals(id))) {
                if (camera.getState().equals(0)) {
                    return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[number],值已存在");
                } else {
                    delete(camera.getId(), projectId1);
                }
            }
        }
        if (Objects.nonNull(pipelineId)) {
            if (validateModel.pipelineIdValidate(Integer.parseInt(pipelineId.toString()), Integer.parseInt(projectId.toString()))) {
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (!cameraService.update(operateMo)) {
            ro.setResultEnum(RoState.FAIL).setMessage("参数无匹配,修改失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/{id}")
    @Permission(value = 1, tags = Constants.API_SUPER)
    public Ro<Camera> delete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId) {
        Ro<Camera> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id", id);
        queryMo.build(Camera.class, projectId);
        queryMo.getEqMap().remove("state");
        if (!cameraService.delete(queryMo)) {
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/logical/{id}")
    @Permission(value = 2, tags = Constants.API_ADMIN)
    public Ro<Camera> logicallyDelete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId) {
        Ro<Camera> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id", id);
        queryMo.build(Camera.class, projectId);
        if (!cameraService.logicallyDelete(queryMo)) {
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }
}
